package com.ekalenchuk.module.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.facebook.api.FacebookProfile;

import com.ekalenchuk.module.domain.user.User;
import com.ekalenchuk.module.dto.registration.UserRegistrationDto;
import com.ekalenchuk.module.dto.session.UserSession;


public class ConverterUtils {

	private static final Logger logger = LoggerFactory.getLogger(ConverterUtils.class);
	
	public static UserRegistrationDto toUserRegistrationDTO(final FacebookProfile profile) {
		UserRegistrationDto dto = new UserRegistrationDto();
		dto.setEmail(profile.getEmail());
		dto.setFacebookId(profile.getId());
		dto.setFirstName(profile.getFirstName());
		dto.setLastName(profile.getLastName());
		dto.setPassword(generateUserPassword(dto, profile.getId(), profile.getFirstName(), profile.getLastName()));
		dto.setLogin(prepareLoginFromPassword(profile.getEmail()));
		return dto;
	}
	
	public static UserSession toUserSession(final UserSession userSession, final User user) {
		userSession.destroy();
		userSession.setEmail(user.getEmail());
		userSession.setFacebookId(user.getFacebookId());
		userSession.setFirstName(user.getFirstName());
		userSession.setLastName(user.getLastName());
		userSession.setId(user.getId());
		userSession.setLogin(user.getLogin());
		return userSession;
	}
	
	public static User toUser(final UserRegistrationDto dto) {
		User user = new User();
		user.setEmail(dto.getEmail());
		user.setFacebookId(dto.getFacebookId());
		user.setFirstName(dto.getFirstName());
		user.setLastName(dto.getLastName());
		user.setLogin(dto.getLogin());
		user.setPassword(dto.getPassword());
		return user;
	}
	
	public static String generateUserPassword(final UserRegistrationDto dto, final String facebookId, final String firstName, final String lastName) {
		String secret = new StringBuilder().append(facebookId).append(dto.hashCode()).append(Math.random()).append(firstName).append(lastName)
				.append(System.currentTimeMillis()).toString();
		
		return md5(secret);
	}
	
	public static String md5(String data) {
		return DigestUtils.md5Hex(data);
	}
	
	public static String prepareLoginFromPassword(final String email) {
		String login = null;
		if(StringUtils.isNotEmpty(email)) {
			login = email.split("@")[0];
		}
		return login;
	}
}
